package com.yy.bootdemo.security.utils;


import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * @author codermy
 * @createTime 2020/7/23
 */
@Component
public class JwtUtils {
/*    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.expiration}")
    private  Long expiration;*/

    private static String secret="my-springsecurity-plus";
    private  static Long expiration=  604800L;

    /**
     * 创建token
     * @param username 用户名
     * @return
     */
    public  String generateToken(String username) {
        return Jwts.builder()
                .signWith(SignatureAlgorithm.HS512, secret)
                .setSubject("guli-user")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
                  //设置token主体部分 ，存储用户信息
                .claim("nickname", username)
                .compact();

    }





    public  String getUserNameFromToken(String jwtToken) {

        if (StringUtils.isEmpty(jwtToken)) return "";
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(secret).parseClaimsJws(jwtToken);
        Claims claims = claimsJws.getBody();
        return JSON.toJSONString(claims) ;
    }

    /**
     * 从token中获取用户名
     * @param token
     * @return
     */
  /*  public static String getUserNameFromToken(String token){
        return getTokenBody(token).getSubject();
    }
*/


    /**
     *  是否已过期
     * @param token
     * @return
     */
    public  boolean isExpiration(String token){
        return getTokenBody(token).getExpiration().before(new Date());
    }

    private static Claims getTokenBody(String token){
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }


 /*   public static void main(String[] args) {
        String string=generateToken("123456");
        System.out.println(string);
        String getUserNameFromToken=getUserNameFromToken("Authorization");
        System.out.println(getUserNameFromToken);

    }*/

}

